package com.yuanshi.food.common.interceptor;

import com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptor;
import com.yuanshi.food.common.annotation.GlobalID;
import com.yuanshi.food.common.enums.ResponseCodeEnum;
import com.yuanshi.food.common.exception.AppException;
import com.yuanshi.food.common.utils.RedisIdWorkerUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;
import java.util.Objects;

/**
 * 全局标识拦截器
 *
 * @author wcy
 * @date 2024/12/03
 */
@Slf4j
@Component
public class GlobalIdInterceptor implements InnerInterceptor {

    @Resource
    private RedisIdWorkerUtil redisIdWorkerUtil;

    @Override
    public void beforeUpdate(Executor executor, MappedStatement ms, Object parameter) {
        // 只处理插入操作
        if (ms.getSqlCommandType() == SqlCommandType.INSERT && parameter != null) {
            try {
                for (Field field : parameter.getClass().getDeclaredFields()) {
                    if (field.isAnnotationPresent(GlobalID.class)) {
                        ReflectionUtils.makeAccessible(field);
                        // 如果字段值为空
                        if (Objects.isNull(field.get(parameter))) {
                            String businessCode = field.getAnnotation(GlobalID.class).businessCode();
                            // 获取全局唯一标识
                            String globalId = redisIdWorkerUtil.nextId(businessCode);
                            ReflectionUtils.setField(field, parameter, globalId);
                        }
                    }
                }
            } catch (IllegalAccessException e) {
                log.error("GlobalIdInterceptor设置全局ID失败", e);
                throw new AppException(ResponseCodeEnum.GLOBAL_ID_SET, e);
            }
        }
    }
}